package com.go.where.family.component.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.go.where.family.component.CustomerCommentComponent;
import com.go.where.family.constants.Constant;
import com.go.where.family.constants.TransmissionCode;
import com.go.where.family.exception.ServerDisponseException;
import com.go.where.family.jersey.api.EasemobMessages;
import com.go.where.family.pojo.CustomerAttentionInfo;
import com.go.where.family.pojo.CustomerCommentInfo;
import com.go.where.family.pojo.CustomerInfo;
import com.go.where.family.pojo.FamilySquareInfo;
import com.go.where.family.scoket.Head;
import com.go.where.family.service.CustomerAttentionService;
import com.go.where.family.service.CustomerCommentService;
import com.go.where.family.service.CustomerService;
import com.go.where.family.service.FamilySquareService;
import com.go.where.family.utils.CommonUtil;
import com.go.where.family.vo.CustomerCommentVo;
import com.go.where.family.vo.EasemobVo;
import com.google.gson.Gson;

@Component("customerCommentComponent")
public class CustomerCommentComponentImpl implements CustomerCommentComponent {

	private static final Logger log = Logger
			.getLogger(CustomerCommentComponentImpl.class);
	private Gson gson;
	@Resource(name = "customerCommentService")
	private CustomerCommentService customerCommentService;
	@Resource(name = "customerAttentionService")
	private CustomerAttentionService customerAttentionService;
	@Resource(name = "familySquareService")
	private FamilySquareService familySquareService;
	@Resource
	private CustomerService customerService;

	public CustomerCommentComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public boolean save(String body, Head head) {
		CustomerCommentVo vo = gson.fromJson(body, CustomerCommentVo.class);
		if (vo != null) {
			/**
			 * 评论类型
			 *1：家族视频，2：家族活动（大类），3：活动回顾，4：课堂回顾，5：家族大会堂（话题墙），
			 *6：家族广场（状态评论）7:家族公益（翠花专栏详情评论）,8：课题评论, 9:课程，id为课程（课堂）id
			 * 
			 */
			CustomerCommentInfo comment = new CustomerCommentInfo();
			comment.setCustomerId(vo.getCustomerId());
			comment.setBigClassId(vo.getBigClassId());
			comment.setSmallClassId(vo.getSmallClassId());
			comment.setCustomerNick(vo.getCustomerNick());
			comment.setCommentContent(vo.getCommentContent());
			comment.setMobile(vo.getMobile());
			comment.setCommentType(vo.getCommentType());
			comment.setPhotoPath(vo.getPhotoPath());
			comment.setActivityId(vo.getActivityId());
			int result = customerCommentService.save(comment);
			if (result > 0) {
				if("6".equals(vo.getCommentType())){
					String squId = vo.getActivityId();
					FamilySquareInfo fsi = familySquareService.queryDetailSquare(squId);
					String squCustomerId = null;
					if(fsi!=null){
						squCustomerId = fsi.getCustomerId();
					}
					CustomerCommentInfo cc = new CustomerCommentInfo();
					cc.setActivityId(vo.getActivityId());
					cc.setCommentType(vo.getCommentType());
					List<String> customerIdList = customerCommentService.queryByTypeAndAid(cc);
					CustomerAttentionInfo attInfo = new CustomerAttentionInfo();
					attInfo.setFollowedId(vo.getCustomerId());
					List<String> attId = this.customerAttentionService.queryByFollowed(attInfo);
					if(customerIdList!=null && ! customerIdList.isEmpty()){
						customerIdList.add(squCustomerId);
						customerIdList.addAll(attId);
					}else{
						customerIdList = new ArrayList<String>();
						customerIdList.add(squCustomerId);
						customerIdList.addAll(attId);
					}
					CustomerInfo ci = customerService.queryByPrimaryKey(vo.getCustomerId(), head);
					String customerNick = ci.getCustomerNick();
					if (StringUtils.isBlank(customerNick)) {
						customerNick = ci.getCustomerId();
					}
					EasemobVo easemobVo = new EasemobVo();
					easemobVo.setUserId(ci.getCustomerId());
					easemobVo.setUserName(customerNick);
					easemobVo
							.setMessageType(Constant.MESSAGE_TYPE_SQUARE_COMMENT);
					easemobVo.setMessageTime(new Date());
					List<String> failedUserId = EasemobMessages.sendMessages(vo
							.getCustomerId(), customerIdList, gson.toJson(easemobVo));
					if (failedUserId != null && !failedUserId.isEmpty()) {
						log
								.info("requestId:" + head.getRequestId()
										+ ",上传评论时，发送消息的失败用户ID："
										+ failedUserId.toString());
					}else{
						log.info("requestId:" + head.getRequestId()+"消息推送成功，用户列表：" + customerIdList);
					}
				}
				return true;
			} else {
				return false;
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",保存客户评论信息时，报文解析异常");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public List<CustomerCommentInfo> queryList(String body, Head head) {
		CustomerCommentVo vo = gson.fromJson(body, CustomerCommentVo.class);
		if (vo != null) {
			Integer currentPage = vo.getPageIndex();
			Integer pageSize = vo.getPageCount();
			Integer pageStart = 1;
			Integer pageEnd = 10;
			if (currentPage != null && pageSize != null) {
				pageStart = (currentPage - 1) * pageSize + 1;
				pageEnd = currentPage * pageSize;
			}
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("pageStart", pageStart);
			paraMap.put("pageEnd", pageEnd);
			paraMap.put("bigClassId", vo.getBigClassId());
			paraMap.put("samllClassId", vo.getSmallClassId());
			paraMap.put("isDelete", Constant.IS_NOT_DELETE);
			paraMap.put("customerId", vo.getCustomerId());
			paraMap.put("commentType", vo.getCommentType());
			paraMap.put("activityId", vo.getActivityId());

			List<CustomerCommentInfo> list = customerCommentService
					.queryList(paraMap);
			if (list != null) {
				for (CustomerCommentInfo comment : list) {
					if (StringUtils.isNotBlank(comment.getPhotoPath())) {
						String[] phs = comment.getPhotoPath().split(";");
						List<String> photos = new ArrayList<String>();
						for (String ph : phs) {
							if (StringUtils.isNotBlank(ph)) {
								photos.add(CommonUtil.getUrlPrefix() + ph);
							}
						}
						comment.setPhotos(photos);
					}
					if (StringUtils.isNotBlank(comment.getHeaderPath())) {
						comment.setHeaderPath(CommonUtil.getUrlPrefix()
								+ comment.getHeaderPath());
					}
					CustomerAttentionInfo cai = new CustomerAttentionInfo();
					cai.setCustomerId(vo.getCustomerId());
					cai.setFollowedId(comment.getCustomerId());
					CustomerAttentionInfo att = customerAttentionService
							.queryParameter(cai);
					if (att != null) {
						comment.setIsAttention(true);
					} else {
						comment.setIsAttention(false);
					}
				}
				return list;
			} else {
				return new ArrayList<CustomerCommentInfo>();
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取评论列表时，参数报文解析异常");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}

	}

}
